/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.Ret;
import com.jfinal.log.Log;
import io.jboot.component.metric.annotation.*;
import io.jboot.component.swagger.ParamType;
import io.jboot.core.rpc.annotation.JbootrpcService;
import io.jboot.utils.EncryptCookieUtils;
import io.jboot.web.controller.annotation.RequestMapping;
import io.jboot.web.controller.validate.CaptchaValidate;
import io.jboot.web.controller.validate.EmptyValidate;
import io.jboot.web.controller.validate.Form;
import io.jboot.web.controller.validate.ValidateRenderType;
import io.jplus.Consts;
import io.jplus.admin.model.Menu;
import io.jplus.admin.model.User;
import io.jplus.admin.service.MenuService;
import io.jplus.admin.service.UserService;
import io.jplus.core.base.BaseController;
import io.jplus.utils.ModelSorter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;

import java.util.List;

@Api(description = "用户登录相关接口文档", basePath = "/admin", tags = "login")
@RequestMapping(value = "/admin", viewPath = Consts.BASE_VIEW_PATH)
public class AdminController extends BaseController {

    public final Log log = Log.getLog(AdminController.class);

    @JbootrpcService
    UserService userService;
    @JbootrpcService
    MenuService menuService;

    @Override
    @RequiresUser
    @EnableMetricCounter
    @EnableMetricConcurrency
    @EnableMetricHistogram
    @EnableMetricMeter
    @EnableMetricTimer
    public void index() {
        User user = getAttr(Consts.JPLUS_USER);
        List<Menu> menuList = menuService.findByUserId(user.getId());
        for (int i=menuList.size()-1;i>0;i--){
            if(0==menuList.get(i).getIsmenu()){
                menuList.remove(i);
            }
        }
        ModelSorter.tree(menuList);
        setAttr("menus", menuList);
        render("index.html");
    }

    @RequiresUser
    public void main() {
        render("main.html");
    }

    public void login() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            redirect("/");
        } else {
            render("login.html");
        }
    }

    @ApiOperation(value = "登录方法", httpMethod = "POST", notes = "user login")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "用户名", paramType = ParamType.FORM, dataType = "string", required = true),
            @ApiImplicitParam(name = "password", value = "密码", paramType = ParamType.FORM, dataType = "string", required = true),
    })
    @Before(POST.class)
    @EmptyValidate(value = {@Form(name = "account", message = "用户名不能为空!"),
            @Form(name = "password", message = "密码不能为空!"),@Form(name = "captcha",message = "验证码不能为空！")})
    @CaptchaValidate(form = "captcha", flashMessage = "验证码不正确！",renderType = ValidateRenderType.REDIRECT)
    public void doLogin(String account, String password) {
        Ret ret;

        UsernamePasswordToken token = new UsernamePasswordToken(account, password, false, getIPAddress());
        Subject subject = SecurityUtils.getSubject();

        try {
            //是否需要进行验证
            if (!subject.isAuthenticated()) {
                subject.login(token);
            }
            ret = Ret.ok();
            User user = userService.findByAccount(account);
            //setSessionAttr(Consts.JPLUS_USER_ID, user.getId());
            EncryptCookieUtils.put(this, Consts.JPLUS_USER_ID, user.getId());
        } catch (AuthenticationException e) {
            ret = Ret.fail(Consts.RET_MSG, e.getMessage());
            this.setFlashAttr(Consts.RET_MSG, e.getMessage());
        } catch (Exception ex) {
            ret = Ret.fail(Consts.RET_MSG, ex.getMessage());
            this.setFlashAttr(Consts.RET_MSG, ex.getMessage());
        }
        if (isAjaxRequest()) {
            renderJson(ret);
        } else {
            redirect(ret.isOk() ? "/admin" : "/admin/login");
        }

    }


    @RequiresUser
    public void logout() {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            SecurityUtils.getSubject().logout();
        }
        render("login.html");
    }

    private void treeNode(List<Menu> menus){
        for (Menu menu : menus) {
            if(menu.getIsmenu().intValue()!=1){
                continue;
            }

            if ("0".equals(menu.getPcode())) {

            }

        }
    }

}
